package com.fyy.content.service.impl;

import com.fyy.content.model.dto.CourseCategoryTreeDTO;
import com.fyy.content.model.po.CourseCategoryPO;
import com.fyy.content.mapper.CourseCategoryMapper;
import com.fyy.content.service.CourseCategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程分类 服务实现类
 * </p>
 *
 * @author fyy
 */
@Slf4j
@Service
public class CourseCategoryServiceImpl extends ServiceImpl<CourseCategoryMapper, CourseCategoryPO> implements CourseCategoryService {

    @Autowired
    private CourseCategoryMapper courseCategoryMapper;
    @Override
    public List<CourseCategoryTreeDTO> queryTreeNodes(String id) {

        List<CourseCategoryTreeDTO> courseCategoryTreeDTOS = courseCategoryMapper.selectTreeNodes(id);
        Map<String, CourseCategoryTreeDTO> treeDTOMap = courseCategoryTreeDTOS.stream().filter(item -> !id.equals(item.getId())).collect(Collectors.toMap(CourseCategoryPO::getId, value -> value, (key1, key2) -> key2));
        List<CourseCategoryTreeDTO> categoryTreeDTOS = new ArrayList<>();
        //遍历每个元素，排除根节点
        courseCategoryTreeDTOS.stream().filter(item -> !id.equals(item.getId())).forEach(item -> {

            //根节点的附属节点直接加入返回List
            if (item.getParentId().equals(id)) {
                categoryTreeDTOS.add(item);
            } else {
                //找到当前节点的父节点
                CourseCategoryTreeDTO parentTreeDTO = treeDTOMap.get(item.getParentId());
                if (parentTreeDTO != null) {
                    if (parentTreeDTO.getChildrenTreeNodes() == null) {
                        parentTreeDTO.setChildrenTreeNodes(new ArrayList<>());
                    }
                    parentTreeDTO.getChildrenTreeNodes().add(item);
                }
            }
        });
        return categoryTreeDTOS;
    }
}
